package com.gxsyh.nantie.phone.consumer.controller;

import com.google.common.cache.Cache;
import com.gxsyh.nantie.commons.dto.PageHelpPhoneDTO;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.phone.consumer.controller.dto.AddDiscussParam;
import com.gxsyh.nantie.phone.provider.api.TbDiscussService;
import com.gxsyh.nantie.phone.provider.api.domain.TbDiscuss;
import okhttp3.ResponseBody;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.KryoCodec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/2/17
 * @time: 10:17
 * @Description:
 */
@RestController
public class DiscussController {

    @Reference(version = "1.0.0")
    TbDiscussService tbDiscussService;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @Resource(name = "CacheCon")
    Cache cache;

    @Resource
    RedissonClient redissonClient;
    /**
     * 增加留言
     * @param addDiscussParam 增加留言实体类
     * @return 成功与否
     */
    @PostMapping(value = "/phone/add/discuss")
    public ResponseResult<Void> addDiscuss(@RequestBody AddDiscussParam addDiscussParam, HttpServletResponse response) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "discuss").body();
        Long id = Long.valueOf(body.string());

        int i = tbDiscussService.addDiscuss(id, addDiscussParam.getContent(), Long.valueOf(authentication.getName()));
        if (i>0){
            return new ResponseResult<>(HttpStatus.OK.value(),"添加留言成功。",null);
        }
        else
        {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"添加留言失败，请检查输入内容。",null);
        }
    }

    /**
     * 查询留言(无缓存做后台使用)
     * @param pageNum 页码
     * @return 分页后的数据
     */
    @GetMapping(value = "/phone/select/all/discuss/now")
    public ResponseResult<PageHelpPhoneDTO> selectAllDiscussNow(@RequestParam int pageNum)
    {
        PageHelpPhoneDTO pageHelpPhoneDTO = tbDiscussService.selectAllDiscuss(pageNum);


        return new ResponseResult<>(HttpStatus.OK.value(),"查询留言成功",pageHelpPhoneDTO);
    }

    /**
     * 查询留言(三级缓存)
     * @param pagenum 页码
     * @return 分页后的数据
     */
    @GetMapping(value = "/phone/select/all/discuss")
    public ResponseResult<PageHelpPhoneDTO> selectAllDiscuss(@RequestParam int pagenum)
    {
        //本地缓存
        PageHelpPhoneDTO cacheIfPresent = (PageHelpPhoneDTO) cache.getIfPresent("discussPage" + pagenum);
        if (cacheIfPresent!=null){
            return new ResponseResult<>(HttpStatus.OK.value(),"查询留言成功",cacheIfPresent);
        }

        //Redis缓存
        RBucket<PageHelpPhoneDTO> discussPage = redissonClient.getBucket("discussPage"+pagenum,new KryoCodec());
        PageHelpPhoneDTO discussPages = discussPage.get();
        if (discussPages==null){
//            查询数据库
            PageHelpPhoneDTO pageHelpPhoneDTO = tbDiscussService.selectAllDiscuss(pagenum);
            discussPage.set(pageHelpPhoneDTO,10, TimeUnit.SECONDS);
            return new ResponseResult<>(HttpStatus.OK.value(),"查询留言成功",pageHelpPhoneDTO);
        }else
        {
//            Redis写进本地缓存
            cache.put("discussPage"+pagenum,discussPages);
            return new ResponseResult<>(HttpStatus.OK.value(),"查询公告成功",discussPages);
        }

    }

    /**
     * 管理员删除留言接口
     * @param discussid
     * @return
     */
    @GetMapping(value = "/phone/admin/delete/discuss")
    public ResponseResult<Void> adminDeleteDiscuss(@RequestParam Long discussid){
        int i = tbDiscussService.deleteDiscuss(discussid);
        if (i>0)
        {
            return new ResponseResult<>(HttpStatus.OK.value(),"删除成功",null);
        }
        else
        {
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"删除失败请重试",null);
        }
    }

    /**
     * 用户删除自己的留言
     * @param discussid
     * @return
     */
    @GetMapping(value = "/phone/user/delete/discuss")
    public ResponseResult<Void> userDeleteDiscuss(@RequestParam Long discussid,HttpServletResponse response){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        TbDiscuss tbDiscussOne = tbDiscussService.selectOneDiscuss(discussid);

        if (Long.valueOf(authentication.getName()).equals(tbDiscussOne.getUserId()))
        {
            int i = tbDiscussService.deleteDiscuss(discussid);
            if (i>0)
            {
                return new ResponseResult<>(HttpStatus.OK.value(),"删除留言成功",null);
            }
            else
            {
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"删除留言失败，请重试",null);
            }
        }
        else
        {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"删除留言失败,不可以删除别人的留言.",null);
        }
    }

}
